package com.travel.find.findfragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.travel.R;
import com.travel.find.findadapter.FindRecyclerViewAdapter;
import com.travel.find.findbean.FindRVBean;
import com.travel.find.findbean.FindTablayoutBean;
import com.travel.find.findconstant.FindConstant;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import tools.Okhttputils;

/**
 * Created by Administrator on 2016/10/18.
 */
public class NewestFragment extends Fragment {
    @Bind(R.id.find_newsest_rv)
    RecyclerView findNewsestRv;
    @Bind(R.id.find_newsest_SwipeRefreshLayout)
    SwipeRefreshLayout findNewsestSwipeRefreshLayout;
    //网络加载数据的字符串
    private String basrUrl;
    //分页的第一页
    private int page=1;
    //最后一个item
    private int lastVisibleItem;
    private int lastItemCount;
    //LinearLayoutManager 线性布局管理器
    private LinearLayoutManager manager;
    //加载数据前的尴尬
    private ProgressDialog pd;
    //分页中用的nb东西此项目必加
    String nb="";
    private View mView;
    //轮播json解析的viewpager集合
    private List<FindTablayoutBean.DataBean.IndexAdListBean> indexAdListBeenList;
    //获取轮播json数据的viewpager集合存储到handler
    private List<FindTablayoutBean.DataBean.IndexAdListBean> handlerIndexAdListBeenList;
    //存储轮播viewpager的图片集合
    private List<String> mList = new ArrayList<>();
    //json解析的recyclerview集合
    private List<FindRVBean.DataBean.ListBean> rvBeenList;
    //获取recyclerview集合存储到handler
    private List<FindRVBean.DataBean.ListBean> handlerrvBeenList;
    //recyclerview的adapter
    private FindRecyclerViewAdapter adapter;
    private int index;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            pd.dismiss();
            switch (msg.what) {
                //加载到viewpager数据
                case 0:
                    handlerIndexAdListBeenList = (List<FindTablayoutBean.DataBean.IndexAdListBean>) msg.obj;
                        for (int i = 0; i < handlerIndexAdListBeenList.size(); i++) {
                            mList.add(indexAdListBeenList.get(i).getPic());
                        }
                    break;
                //加载RecyclerView数据
                case 1:
                    if(page==1) {
                        handlerrvBeenList = (List<FindRVBean.DataBean.ListBean>) msg.obj;
                        adapter = new FindRecyclerViewAdapter(getActivity(), handlerrvBeenList, handlerIndexAdListBeenList);
                        findNewsestRv.setAdapter(adapter);
                        lastVisibleItem = manager.findLastVisibleItemPosition();
                    }else{
                        adapter.rush((List<FindRVBean.DataBean.ListBean>) msg.obj, false);
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.newestfragment, container, false);
        ButterKnife.bind(this, mView);
        initview();
        //加载viewpager的数据
        initdata1();
        //加载recycleview的数据
        initdata2(true);
        //刷新数据
        refresh();
        return mView;
    }
    //初始化数据
    private void initview() {
        manager = new LinearLayoutManager(getActivity());
        findNewsestRv.setLayoutManager(manager);
        //dialog初始化
        pd=new ProgressDialog(getActivity());
        Bundle bundle = getArguments();
         index = bundle.getInt("index");
//        if (index != 0) {
//            adapter.getBannerLayout().setVisibility(View.GONE);
////            //设置轮播是否可见
////            findNewsestRv.
////            manager.findViewByPosition(0).setVisibility(View.GONE);
//        }
        //判断接口
        if (index == 0) {
            basrUrl = FindConstant.RECYCLERVIEW1;
        } else if (index == 2) {
            basrUrl =FindConstant.CLEVER;
        } else if(index==3){
            basrUrl = FindConstant.BABY;
        } else if (index == 4) {
            basrUrl =FindConstant.ISLAND;
        } else if(index==5){
            basrUrl = FindConstant.DRIVING;
        }

    }

//加载viewpager的数据
    private void initdata1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //获取轮播数据
                String vpJson = null;
                try {
                    vpJson = Okhttputils.getInstance().run(FindConstant.TABLAYOUT_VIEWPAGER);
                    String data = JSONObject.parseObject(vpJson).getString("data");
                    String indexAdList = JSONObject.parseObject(data).getString("indexAdList");
                    indexAdListBeenList = JSONArray.parseArray(indexAdList, FindTablayoutBean.DataBean.IndexAdListBean.class);
                    //将轮播数据发送到handler
                    if (indexAdListBeenList.size() != 0 && indexAdListBeenList != null) {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = indexAdListBeenList;
                        mHandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //网络获取热菜yclerview数据回传到handler
    private void initdata2(boolean b) {
        if (b) {
            pd.setMessage("正在加载数据...");
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.show();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                   //获取recyclerview数据
//                    Log.e("tag","???????"+basrUrl);
                    String rvJson = Okhttputils.getInstance().run(basrUrl+page+FindConstant.RECYCLERVIEW2+nb);
                    String data1 = JSONObject.parseObject(rvJson).getString("data");
                    nb=JSONObject.parseObject(data1).getString("nextTime");
                    String list = JSONObject.parseObject(data1).getString("list");
                    rvBeenList = JSONArray.parseArray(list, FindRVBean.DataBean.ListBean.class);
                    //将recyclerview数据发送到handler
                    if (rvBeenList.size() != 0 && rvBeenList != null) {
                        Message msg = Message.obtain();
                        msg.what = 1;
                        msg.obj = rvBeenList;
                        mHandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //刷新数据
    private void refresh() {
        //加载更多
        findNewsestRv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(final RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                lastItemCount = manager.getItemCount();
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            if (handlerrvBeenList.size() != 0) {
                                page++;
                                FindRecyclerViewAdapter.load_more_status = 0;
                                initdata2(false);
                            } else {
                                FindRecyclerViewAdapter.load_more_status = 1;
                                initdata2(false);
                            }
                        }
                    });
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = manager.findLastVisibleItemPosition();
            }
        });
        //设置刷新时动画的颜色  可以设置4个
        findNewsestSwipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light
        );
        //下拉刷新
        findNewsestSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (page == 1) {
                            initdata2(false);
                        }
                        findNewsestSwipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
